package com.dosin.crowno.utils;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


    /*
    文件读写操作

     */
public class FileWriteAndRead {


    public static void writeFile(String filePath,String cookieStr){

        FileOutputStream outputStream = null;
        FileChannel channel = null;

        try {

            File file = new File(filePath);
            if(!file.exists()){

                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
            outputStream = new FileOutputStream(file);
            channel = outputStream.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put(cookieStr.getBytes());
            buffer.flip();     //此处必须要调用buffer的flip方法
            channel.write(buffer);
            System.out.println(buffer.toString());
        }catch (IOException e) {
            e.printStackTrace();
        }finally {

            try {
                if(channel != null) {
                    channel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {

                if(outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }




    public static String readFile(String filePath) {

        StringBuffer s = new StringBuffer();
        FileInputStream fin = null;
        FileChannel channel = null;
        try {
            fin = new FileInputStream(filePath);
            // 获取通道
            channel = fin.getChannel();
            // 创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            // 读取数据到缓冲区
            channel.read(buffer);
            buffer.flip();


            while (buffer.remaining() > 0) {
                byte b = buffer.get();
                s.append((char) b);
                //System.out.print(((char) b));
            }
            System.out.print(s);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (channel != null) {
                    channel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fin != null) {
                    fin.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return s.toString();
    }
    }
